package routers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"net/http"
	"os"
	"strings"
	config2 "tinyrdm/server/config"
	"tinyrdm/server/controllers"
	"tinyrdm/server/middleware"
	"tinyrdm/server/models"
)

func InitRoutes() {
	config := config2.Config

	userController := controllers.NewUserController()

	logs.Info("baseApi", config.BaseApi)

	preferences := &controllers.PreferencesController{}
	preferences.SetAppVersion(config2.Version)

	ns := beego.NewNamespace(config.BaseApi,
		beego.NSRouter("/browser", &controllers.BrowserController{}, "post:Handler"),
		beego.NSRouter("/cli", &controllers.CliController{}, "post:Handler"),
		beego.NSRouter("/connection", &controllers.ConnectionController{}, "post:Handler"),
		beego.NSRouter("/monitor", &controllers.MonitorController{}, "post:Handler"),
		beego.NSRouter("/preferences", &controllers.PreferencesController{}, "post:Handler"),
		beego.NSRouter("/pubsub", &controllers.PubSubController{}, "post:Handler"),
		beego.NSRouter("/system", &controllers.SystemController{}, "post:Handler"),

		beego.NSRouter("/user/login", userController, "post:Login"),
		beego.NSRouter("/user/info", userController, "get:User"),
		beego.NSRouter("/user/register", userController, "post:Register"),
		beego.NSRouter("/oauth2", &controllers.Oauth2Controller{}),
		beego.NSRouter("/oauth2/callback", &controllers.Oauth2Controller{}, "post:Callback"),
	)
	beego.AddNamespace(ns)

	beego.InsertFilter(fmt.Sprintf("%s/**", config.BaseApi), beego.BeforeRouter, middleware.AuthFilter)

	beego.Router(fmt.Sprintf("%s/config.js", config.ContextPath), &controllers.ConfigController{})
	removeConfigJs("frontend/dist/config.js")
	// portal static assets
	//beego.SetStaticPath(config.ContextPath, "static/web")
	beego.SetStaticPath(config.ContextPath, "frontend/dist")
	beego.Get("/", func(ctx *context.Context) {
		ctx.Redirect(301, fmt.Sprintf("%s/index.html", config.ContextPath))
	})

	beego.ErrorHandler("404", func(writer http.ResponseWriter, request *http.Request) {
		accept := request.Header.Get("accept")
		logs.Warn(request.RequestURI, "404", accept)
		if strings.Contains(accept, "json") {
			writer.Header().Set("content-type", "application/json")
			writer.WriteHeader(200)
			resp := models.RespData{
				Code: -2,
				Msg:  "server error",
			}
			str, _ := json.Marshal(&resp)
			writer.Write(str)
		} else {
			writer.WriteHeader(404)
			writer.Write([]byte(""))
		}
	})
}

func removeConfigJs(path string) {
	_, err := os.Stat(path)
	if err != nil {
		return
	}
	err = os.Remove(path)
	if err != nil {
		logs.Warn("removeConfigJs fail", err)
	}
}
